package com.example.demo.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateToStamp {

    /**
     * 将时间转换为时间戳
     *
     * @param s 传入时间
     * @return
     * @throws ParseException
     */
    public static long dateToStamp(String s) throws ParseException {


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = simpleDateFormat.parse(s);

        long ts = date.getTime() / 1000;


        return ts;
    }

    /**
     * 将时间戳转换为时间格式 yyyy-MM-dd HH:mm:ss 格式
     *
     * @param date 时间戳入参
     * @return
     */
    public static String stampToDate(long date) {
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date * 1000), ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = dateTime.format(formatter);
        return formattedDateTime;
    }


    /**
     * 获取现在长度为10的时间戳
     *
     * @return
     */
    public static int getTimeStamp() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    /**
     * 获取现在长度为10的时间戳
     *
     * @return
     */
    public static Long getTimeStampLong() {
        return System.currentTimeMillis() / 1000;
    }

    public static void main(String[] args) throws ParseException {
        long times = System.currentTimeMillis() / 1000;
        System.out.println(times);
        long time1 = dateToStamp("2020-08-01 00:00:00");
        System.out.println(time1);
    }
}
